<template>
  <div class="app-toolbox-xmap-navbar">
    <div class="app-toolbox-xmap-navbar__items-wrapper">
      <div class="app-toolbox-xmap-navbar__items-wrapper__item--topic">
        <label class="app-toolbox-xmap-navbar__items-wrapper__item--topic__label">专题导图</label>
        <t-button class="app-toolbox-xmap-navbar__items-wrapper__item--topic__btn" size="mini" :loading="!store.topic.state.enabled.insert" icon="biaoqian" :type="store.current.mid === store.topic.state.mid ? 'success' : 'primary'" @click="handleSwitch(store.topic.state.mid)" @icon-click="handleIconClick(store.topic.state.mid)" :key="store.topic.state.mid">{{ fixed(store.topic.name) }}</t-button>
      </div>
      <div class="app-toolbox-xmap-navbar__items-wrapper__item--module">
        <label class="app-toolbox-xmap-navbar__items-wrapper__item--module__label">模块导图</label>
        <div class="app-toolbox-xmap-navbar__items-wrapper__item--module__btn-wrapper">
          <t-button class="app-toolbox-xmap-navbar__items-wrapper__item--module__btn" v-for="module in navModules" size="mini" :loading="!module.state.enabled.insert" icon="biaoqian" :type="store.current.mid === module.state.mid ? 'success' : 'primary'" @click="handleSwitch(module.state.mid)" @icon-click="handleIconClick(module.state.mid)" :key="module.state.mid">{{ fixed(module.name) }}</t-button>
          <t-dropdown v-show="isShowMore">
            <t-button slot="btn" type="primary" size="mini">其他</t-button>
            <t-dropdown-menu slot="list">
              <t-dropdown-item v-for="module in dropModules" :key="module.state.mid"><t-button size="full" type="primary" :loading="!module.state.enabled.insert" icon="biaoqian" :type="store.current.mid === module.state.mid ? 'success' : 'primary'" @click="handleSwitch(module.state.mid)" :key="module.state.mid" @icon-click="handleIconClick(module.state.mid)">{{ module.name }}</t-button></t-dropdown-item>
            </t-dropdown-menu>
          </t-dropdown>
          <t-button size="mini" type="update" @click="addTopicModule">添加</t-button>
        </div>
      </div>
    </div>
    <div class="app-toolbox-xmap-navbar__funcs-wrapper">
      <div class="app-toolbox-xmap-navbar__funcs-wrapper__func--progress-bar-wrapper"><t-progress-bar :percent="currentPercent" @click="handleTomatoProgressBarClick"><div slot="title">番茄进度</div><div slot="time">{{ currentTime }}</div></t-progress-bar></div>
      <div class="app-toolbox-xmap-navbar__funcs-wrapper__func--synchronize-wrapper"><t-synchronize v-if="currentItem" :state="currentItem.state.synchronize" @force-synchronize="handleForceSynchronize"></t-synchronize></div>
      <div class="app-toolbox-xmap-navbar__funcs-wrapper__func--btn-wrapper"><t-button size="mini" type="primary" @click="">管理</t-button></div>
      <div class="app-toolbox-xmap-navbar__funcs-wrapper__func--btn-wrapper"><t-button size="mini" type="danger" @click="handleExit">退出</t-button></div>
    </div>
    <div slot="other">
      <t-item-dialog :store="store" :visible="store.dialog.visible" :title="store.dialog.title" @close="finalizeDialog" v-transfer></t-item-dialog>
      <t-loading-dialog :visible="store.loadingDialog.visible" v-transfer></t-loading-dialog>
      <t-tomato-dialog :visible="store.tomatoDialog.visible" :type="store.tomatoDialog.type" :tomatoState="currentTomatoState" @create="handleCreate" @quit="handleQuit" @cancel="handleCancel" v-transfer></t-tomato-dialog>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue';
  import TButton from '@/components/button';
  import TProgressBar from '@/components/progress-bar';
  import TSynchronize from '@/components/synchronize';
  import utils from '@/app/utils/utils';
  import tDropdown from '@/components/dropdown';
  import tDropdownMenu from '@/components/dropdown/dropdown-menu';
  import tDropdownItem from '@/components/dropdown/dropdown-item';
  import tItemDialog from '@/app/toolbox/xmap/navbar/item-dialog';
  import tLoadingDialog from '@/app/toolbox/xmap/navbar/loading-dialog';
  import tTomatoDialog from '@/app/toolbox/xmap/navbar/tomato-dialog';
  import transfer from '../../../directives/transfer';

  export default {
    name: 'app-toolbox-xmap-navbar',
    directives: { transfer },
    components: {
      TButton,
      TProgressBar,
      TSynchronize,
      tDropdown,
      tDropdownMenu,
      tDropdownItem,
      tItemDialog,
      tLoadingDialog,
      tTomatoDialog,
    },
    props: {
      store: {
        type: Object,
        required: true,
      },
    },
    data() {
      return {
        threshold: 4,
        seq: [],
        avaiableTime: -1,
        avaiableTimer: -1,
        avaiable: false,
        maxAvaiableTime: 60000,
        workTime: -1,
        workTimer: -1,
        workTotalTime: 1500000,
        restTime: -1,
        restTimer: -1,
        restTotalTime: 300000,
        state: '',
      };
    },
    computed: {
      editing() {
        return this.store.editing;
      },
      currentState() {
        if (this.workTime !== -1) {
          return 'work';
        } else if (this.restTime !== -1) {
          return 'rest';
        }
        return 'other';
      },
      currentPercent() {
        if (this.currentState === 'work') {
          return (this.workTime / this.workTotalTime) * 100;
        }
        if (this.currentState === 'rest') {
          return (this.restTime / this.restTotalTime) * 100;
        }
        return 0;
      },
      currentTime() {
        if (this.currentState === 'work') {
          const min = (this.workTime / 1000) / 60;
          const sec = (this.workTime / 1000) % 60;
          return `${window.parseInt(min)}分${sec}秒`;
        }
        if (this.currentState === 'rest') {
          const min = (this.restTime / 1000) / 60;
          const sec = (this.restTime / 1000) % 60;
          return `${window.parseInt(min)}分${sec}秒`;
        }
        return '00:00';
      },
      currentTotalTime() {
        if (this.currentState === 'work') {
          const min = (this.workTotalTime / 1000) / 60;
          const sec = (this.workTotalTime / 1000) % 60;
          return `${window.parseInt(min)}分${sec}秒`;
        }
        if (this.currentState === 'rest') {
          const min = (this.restTotalTime / 1000) / 60;
          const sec = (this.restTotalTime / 1000) % 60;
          return `${window.parseInt(min)}分${sec}秒`;
        }
        return '00:00';
      },
      currentTomatoState() {
        return {
          currentState: this.currentState,
          currentPercent: this.currentPercent,
          currentTime: this.currentTime,
          currentTotalTime: this.currentTotalTime,
        };
      },
      currentItem() {
        if (this.store.topic.state.mid === this.store.current.mid) {
          return this.store.topic;
        }
        let citem = null;
        Object.values(this.store.modules).forEach((item) => {
          if (item.state.mid === this.store.current.mid) {
            citem = item;
          }
        });
        return citem;
      },
      navModules() {
        const nav = [];
        let count = 0;
        Object.values(this.seq).forEach((mid) => {
          if (count < this.threshold) {
            Object.values(this.store.modules).forEach((item) => {
              if (item.state.mid === mid) {
                nav.push(item);
              }
            });
          }
          count += 1;
        });
        return nav;
      },
      dropModules() {
        const drops = [];
        let count = 0;
        Object.values(this.seq).forEach((mid) => {
          if (count >= this.threshold) {
            Object.values(this.store.modules).forEach((item) => {
              if (item.state.mid === mid) {
                drops.push(item);
              }
            });
          }
          count += 1;
        });
        return drops;
      },
      isShowMore() {
        return this.dropModules.length !== 0;
      },
    },
    created() {
      Object.values(this.store.modules).forEach((item) => {
        this.seq.push(item.state.mid);
      });
      this.enableAvaiable();
      this.createAvaiableTimer();
      this.$parent.$on('editing', () => {
        this.enableAvaiable();
        this.createAvaiableTimer();
      });
      this.$nextTick(() => {
        this.store.tomatoDialog.type = 'create';
        this.openTomatoDialog();
      });
    },
    methods: {
      create() {
        this.createTomatoTimer();
      },
      destroy() {
        this.$parent.$destroy();
        this.clearTomatoTimer();
        this.clearRestTimer();
        this.clearAvaiableTimer();
        this.$router.push('/service/topic');
      },
      handleCreate() {
        this.closeTomatoDialog();
        this.create();
      },
      handleQuit() {
        this.closeTomatoDialog();
        this.destroy();
      },
      handleCancel() {
        this.closeTomatoDialog();
      },
      handleTomatoProgressBarClick() {
        if (this.currentState === 'other') {
          this.store.tomatoDialog.type = 'create';
        } else {
          this.store.tomatoDialog.type = 'info';
        }
        this.openTomatoDialog();
      },
      handleExit() {
        this.store.tomatoDialog.type = 'quit';
        this.openTomatoDialog();
      },
      openTomatoDialog() {
        this.store.tomatoDialog.visible = true;
      },
      closeTomatoDialog() {
        this.store.tomatoDialog.visible = false;
      },
      enableAvaiable() {
        this.avaiable = true;
      },
      disableAvaiable() {
        this.avaiable = false;
      },
      clearAvaiableTimer() {
        window.clearTimeout(this.avaiableTimer);
        this.avaiableTimer = -1;
      },
      clearRestTimer() {
        window.clearTimeout(this.restTimer);
        this.restTimer = -1;
        this.restTime = -1;
      },
      clearTomatoTimer() {
        window.clearTimeout(this.workTimer);
        this.workTimer = -1;
        this.workTime = -1;
      },
      createAvaiableTimer() {
        if (this.avaiableTimer !== -1) {
          this.clearAvaiableTimer();
        }
        this.avaiableTime = 0;
        this.avaiableTimer = window.setInterval(() => {
          this.avaiableTime += 1000;
          if (this.avaiableTime === this.maxAvaiableTime) {
            this.disableAvaiable();
            this.clearAvaiableTimer();
          }
        }, 1000);
      },
      createRestTimer() {
        this.restTime = 0;
        this.store.tomatoDialog.type = 'info';
        this.openTomatoDialog();
        this.restTimer = window.setInterval(() => {
          this.restTime += 1000;
          if (this.restTime === this.restTotalTime) {
            this.clearRestTimer();
          }
        }, 1000);
      },
      createTomatoTimer() {
        this.workTime = 0;
        this.workTimer = window.setInterval(() => {
          if (this.avaiable) {
            this.workTime += 1000;
          }
          if (this.workTime === this.workTotalTime) {
            this.clearTomatoTimer();
            this.createRestTimer();
            this.punch();
            this.currentItem.todayTomatoAmount += 1;
            this.currentItem.tomatoAmount += 1;
          }
        }, 1000);
      },
      punch() {
        const token = this.$stateHub.csrf;
        const target = this.getPunchUrl();
        this.$http.request({
          url: target,
          method: 'put',
          data: {
            token,
          },
          transformRequest: [(data) => {
            const encodeToken = encodeURIComponent(data.token);
            return `_csrf=${encodeToken}`;
          }],
        }).then((response) => {
          this.$stateHub.csrf = response.data.csrf;
          this.$noticeHub.tomato({ message: '获得一颗 [专题番茄], 评价一下这颗番茄呗！', duration: 1800000 });
        }).catch((error) => {
          this.$stateHub.csrf = error.response.data.csrf;
        });
      },
      getPunchUrl() {
        if (this.currentItem.state.type === 'topic') {
          return `api/topics/${this.currentItem.id}/actions/punch`;
        }
        if (this.currentItem.state.type === 'module') {
          return `api/modules/${this.currentItem.id}/actions/punch`;
        }
        return null;
      },
      handleSwitch(mid) {
        if (this.store.current.mid === mid) return;
        this.modify(mid);
        this.store.current.mid = mid;
      },
      handleIconClick(mid) {
        this.initDialog(mid);
      },
      initDialog(mid) {
        this.store.current.mid = mid;
        this.store.dialog.title = '管理导图';
        this.store.dialog.visible = true;
        this.store.current.input.name = this.currentItem.name;
        this.store.current.input.synopsis = this.currentItem.synopsis;
      },
      finalizeDialog() {
        this.store.dialog.title = '';
        this.store.dialog.visible = false;
      },
      modify(mid) {
        const index = this.seq.indexOf(mid);
        if (index >= this.threshold) {
          this.seq.splice(index, 1);
          this.seq.splice(this.threshold - 1, 0, mid);
        }
      },
      fixed(name) {
        if (name.length > 5) {
          name = `${name.substring(0, 4)} ..`;
        }
        return name;
      },
      handleForceSynchronize() {
        this.currentItem.state.synchronize = 'force-todo';
      },
      addTopicModule() {
        const topicId = this.store.topic.id;
        const url = 'api/modules';
        const name = '模块主题';
        const synopsis = '为了更好的明天';
        const xmapContent = utils.initXmapContent(name);
        this.$http.request({
          url,
          method: 'post',
          data: {
            name,
            synopsis,
            xmapContent,
            topicId,
          },
          transformRequest: [(data) => {
            const encodeName = encodeURIComponent(data.name);
            const encodeSynopsis = encodeURIComponent(data.synopsis);
            const encodeXmapContent = encodeURIComponent(data.xmapContent);
            const encodeTopicId = encodeURIComponent(data.topicId);
            return `name=${encodeName}&synopsis=${encodeSynopsis}&xmapContent=${encodeXmapContent}&topicId=${encodeTopicId}`;
          }],
        }).then((response) => {
          this.updateKity(response.data);
        }).catch(() => {
        });
      },
      updateKity(item) {
        const mid = this.store.state.midLen;
        const index = this.store.state.moduleLen;
        Vue.set(this.store.modules, index, {});
        Vue.set(this.store.modules[index], 'id', item.id);
        Vue.set(this.store.modules[index], 'name', item.name);
        Vue.set(this.store.modules[index], 'synopsis', item.synopsis);
        Vue.set(this.store.modules[index], 'createTime', item.createTime);
        Vue.set(this.store.modules[index], 'updateTime', item.updateTime);
        Vue.set(this.store.modules[index], 'tomatoAmount', item.tomatoAmount);
        Vue.set(this.store.modules[index], '', '');
        Vue.set(this.store.modules[index], 'state', {});
        Vue.set(this.store.modules[index].state, 'mid', mid);
        Vue.set(this.store.modules[index].state, 'timer', null);
        Vue.set(this.store.modules[index].state, 'synchronize', 'success');
        Vue.set(this.store.modules[index].state, 'enabled', {});
        Vue.set(this.store.modules[index].state.enabled, 'insert', false);
        Vue.set(this.store.modules[index].state.enabled, 'update', false);
        Vue.set(this.store.modules[index].state.enabled, 'show', true);
        Vue.set(this.store.modules[index].state, 'init', false);
        Vue.set(this.store.modules[index].state, 'type', 'module');
        this.store.state.midLen += 1;
        this.store.state.moduleLen += 1;
        this.seq.push(mid);
        this.modify(mid);
        this.store.current.mid = mid;
      },
    },
  };
</script>